package com.demo.config;

import com.demo.entity.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        logger.info("进入拦截器");
        registry.addInterceptor(new SessionHandlerInterceptors()).addPathPatterns("/admin/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        logger.info("进入跨域访问");
    }
}

class SessionHandlerInterceptors implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect("/m1");
            return false;
        }
        return true;
    }

}
